package com.foyekoo.project001.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.foyekoo.project001.BR;
import com.foyekoo.project001.R;
import com.foyekoo.project001.model.Bill;
import com.foyekoo.project001.model.BillItemVM;
import com.foyekoo.project001.utils.BaseDataBindingAdapter;
import com.foyekoo.project001.utils.BillUtil;
import com.foyekoo.project001.utils.TimeUtil;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class BillFragment extends BaseFragment {


    private RecyclerView recyclerView;

    private List<BillItemVM> vms = new ArrayList<>();

    private BaseDataBindingAdapter adapter;

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_bill, null);
        Button btn = view.findViewById(R.id.btn_clear);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BillUtil.updateCurDay("2018-08-04");
                initBill();
            }
        });

        initBill();

        return view;
    }

    private void initBill() {
        vms.clear();
        List<Bill> bills = BillUtil.getAllBill();
        for (int i = 0; i < bills.size(); i++) {
            BillItemVM vm = new BillItemVM();
            vm.coin.set(bills.get(i).coinNum + "");
            vm.date.set(bills.get(i).date + "");
            vm.prize.set(bills.get(i).prizeNum + "");

            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = null;
            if (bills.get(i).coinNum == 0) {
                result = "0";
            } else {
                result = numberFormat.format((float) bills.get(i).prizeNum / (float) bills.get(i).coinNum * 100);
            }

            vm.prizePercent.set("中奖率：" + result + "%");
            if (i == 0) {
                vm.isFirst.set(true);
            } else {
                vm.isFirst.set(false);
            }
            vms.add(vm);
        }

        recyclerView = view.findViewById(R.id.recycle_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new BaseDataBindingAdapter(getContext(), R.layout.widget_bill_list_item, vms, BR.BillItemVM);
        recyclerView.setAdapter(adapter);


    }
}
